var columns = [
    {
        field: 'index',
        title: '序号',
        align:"center",
        formatter:function(value, row, index){
            return index+1;
        }
    },{
        field: 'lessonNumber',
        align: 'center',
        title: lessonType == "lesson" ? '课程名称' : "章节名称"
    },{
        field: 'startTime',
        align: 'center',
        title: '课程时间',
        visible: lessonType == "lesson" ? true : false
    },{
        field: 'desc',
        align: 'center',
        title: '课程介绍',
        formatter: function (value, row, index) {
            return row.desc.substring(0,10);
        },
        visible: lessonType == "lesson" ? true : false
    }, {
        field: 'videoUrl',
        align: 'center',
        title: '视频URL',
        visible: lessonType == "lesson" ? false : true,
        formatter: function (value, row, index) {
            return row.videoUrl.substring(0,10);
        },
    },{
        field: 'operator',
        title: '操作',
        align: 'center',
        formatter: function (value, row, index) {
            if("show" != queryType){
                return '<button class="btn btn-warning btn-icon-anim btn-circle" style="width: 20px;height: 20px;margin-left: 10px;" onclick="addLesson.showScheduleDet(&quot;'+row.id+'&quot;)"' +
                    ' title="查看"> <i class="fa fa-eye"></i></button>'+
                    '<button class="btn btn-warning btn-icon-anim btn-circle" style="width: 20px;height: 20px;margin-left: 10px;" onclick="addLesson.updateSchedule(&quot;'+row.id+'&quot;)"' +
                    ' title="修改"> <i class="fa fa-pencil"></i></button>'+
                    '<button class="btn btn-warning btn-icon-anim btn-circle" style="width: 20px;height: 20px;margin-left: 10px;" onclick="addLesson.delSchedule(&quot;'+row.id+'&quot;)"' +
                    ' title="删除"> <i class="fa fa-minus"></i></button>';
            }else {
                $('#tableList').bootstrapTable('hideColumn', 'operator');
            }
    }}];
var type='';
var gocode='/lesson/addLesson';
var role='';
var addLesson={
    addLessonInit:function(){
        sessionStorage.removeItem("memberList");
        $("#cancel").click(function(){
            loadUtil = new Load($);
            loadUtil.load({
                container:'#homeContent',
                url: application.contextPath+backUrl
            });
            return false;
        });
        tinymce.init({convert_urls: false,
            readonly:queryType=="show",
            selector: '.tinymce',
            height: 300,
            plugins: [
                'advlist autolink lists link image charmap print preview anchor',
                'searchreplace visualblocks code fullscreen',
                'insertdatetime media table contextmenu paste code'
            ],
            toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
            init_instance_callback:addLesson.updateInit
        });
    },
    queryCatAll:function(str){
        $.ajax({
            url:application.contextPath+"/lesson/queryCatAll?catType="+str,
            type:"GET",
            success:function (res) {
                var html='';
                if(res.data !=''){
                    for (var i=0; res.data.length>i;i++){
                        html+='<option value="'+res.data[i].id+'">'+res.data[i].cateName+'</option>';
                    }
                }
                $("#categoryId").html(html);
            }
        })
   },
    showAddLessonTeacher:function(){
        $.get(
            application.contextPath+"/lesson/showAddLessonTeacher",
            function (res) {
                layer.open({
                    type:1,
                    title:'选择任课老师',
                    content:res,
                    maxmin:true,//最大，最小开关
                    shade:0.5,//遮盖层模糊度
                    anim:1,//打开跟关闭动画
                    scrollbar:true,//是否设置滚轮
                    area:["1080px","500px"]
                })
            }
        )
    },
    scheduleInit:function(){
        pubForm.getBootTable("#tableList","/lesson/queryScheduleList","",$("#lessonId").val());
    },
    showScheduleDet:function(scheduleId){
        $.get(
            application.contextPath+"/lesson/showScheduleDet?scheduleId="+scheduleId+"&lessonType="+lessonType,
            function (res) {
                layer.open({
                    type:1,
                    title:lessonType == "lesson" ? '课时详情' : '章节详情',
                    content:res,
                    maxmin:true,//最大，最小开关
                    shade:0.5,//遮盖层模糊度
                    anim:1,//打开跟关闭动画
                    scrollbar:true,//是否设置滚轮
                    area:["1080px","auto"]
                })
            }
        )
    },
    updateSchedule:function(scheduleId){
        $.get(
            application.contextPath+"/lesson/showUpdateSchedule?scheduleId="+scheduleId+"&lessonType="+lessonType,
            function (res) {
                layer.open({
                    type:1,
                    title:lessonType == "lesson" ? '课时修改' : '章节修改',
                    content:res,
                    maxmin:true,//最大，最小开关
                    shade:0.5,//遮盖层模糊度
                    anim:1,//打开跟关闭动画
                    scrollbar:true,//是否设置滚轮
                    area:["1080px","auto"]
                })
            }
        )
    },
    delSchedule:function(scheduleId){
        pubForm.delRow(scheduleId,"/lesson/delScheduleById","/lesson/queryScheduleList","#tableList",$("#lessonId").val())
    },
    showAddLessonSchedule:function(){
        var lessonId=$("#lessonId").val();
        if("" != lessonId && null != lessonId && undefined != lessonId){
            $.get(
                application.contextPath+"/lesson/showAddLessonSchedule?lessonId="+$("#lessonId").val()+"&lessonType="+lessonType,
                function (res) {
                    layer.open({
                        type:1,
                        title:lessonType == "lesson" ? '课时创建' : '章节创建',
                        content:res,
                        maxmin:true,//最大，最小开关
                        shade:0.5,//遮盖层模糊度
                        anim:1,//打开跟关闭动画
                        scrollbar:true,//是否设置滚轮
                        area:["1080px","auto"]
                    })
                }
            )
        }else {
            layer.msg("请基本信息完成后新增",{icon:5});
        }
    },
    commitAdd:function (form) {
        var data = {};
        var array = $(form).serializeArray();
        for(var index in array){
            data[array[index]['name']] = array[index]['value']
        }
        data.id=  $("#lessonId").val();
        data.lessonType=type;
        data.mDesc=tinyMCE.editors[0].getContent();

        if(!jsEcc.isNull(data.lessonName)){
            layer.msg('名称不能为空',{icon:5});
            return false;
        }
        if("lesson" ==  lessonType){
            if(role == "1" || role =="2"){
            }else {
                data.hot='0'
            }
            if(!jsEcc.isNull(data.stock)){
                layer.msg('库存设置不能为空',{icon:5});
                return false;
            }
            if("" ==data.classSize ){
                data.classSize="0";
            }else {
                if(parseInt(data.classSize)<parseInt(data.stock)){
                    layer.msg('班级人数不能小于库存',{icon:5});
                    return false;
                }
            }
            if(!jsEcc.isNull(data.startDate)){
                layer.msg('开课时间不能为空',{icon:5});
                return false;
            }
            if(!jsEcc.isNull(data.endDate)){
                layer.msg('结束时间不能为空',{icon:5});
                return false;
            }else {
                if(data.startDate>data.endDate){
                    layer.msg('结束时间不能小于开课时间',{icon:5});
                    return false;
                }
            }
            if(!jsEcc.isNull(data.teacherId)){
                layer.msg('任课老师不能为空',{icon:5});
                return false;
            }
        }else if("voide" == lessonType){
            if(!jsEcc.isNull(data.videoUrl)){
                layer.msg('视频URL不能为空',{icon:5});
                return false;
            }
        }else {
            if(!jsEcc.isNull(data.classSize)){
                layer.msg('可购课程数不能为空',{icon:5});
                return false;
            }
            data.lessonDate="1";
            data.stock="10000";
        }

        if(!jsEcc.isNull(data.mDesc)){
            layer.msg('描述不能为空',{icon:5});
            return false;
        }
        $.ajax({
            url:application.contextPath+gocode,
            type:"POST",
            contentType: "application/json; charset=utf-8",
            dataType:"json",
            data:JSON.stringify({lesson:data}),
            success:function (res) {
                var remsg='';
                if("lesson" == lessonType){
                    remsg="课程"
                }else if("voide" == lessonType){
                    remsg="视频";
                }else {
                    remsg="套餐";
                }
                var retype='';
                gocode == "/lesson/addLesson" ? retype= "创建" : retype= "更新";
                if(res.isSuccess){
                    $("#lessonId").val(res.data);
                    $("#ObjId").val(res.data);
                    if("meal" != lessonType){
                        $("#topUpImgs").show();
                        $("#topPhoto").show();//课程图片
                    }
                    gocode ='/lesson/updateLesson';
                    layer.msg(remsg+retype+"成功",{icon:1})
                }else {
                    gocode == "/lesson/addLesson";
                    layer.open({
                        title:"加载失败!",
                        content:res.message
                    });
                }
            }
        });
        return false;
    },
    scheduleRef:function () {
        var opt={
            url:application.contextPath+"/lesson/queryScheduleList",
            query:{size:5,page:1,"parm":$("#lessonId").val()},
            silent:true
        };
        $('#tableList').bootstrapTable('refresh',opt);
    },
    updateInit:function () {
        if("add" != queryType){
            $.ajax({
                url:application.contextPath+"/lesson/queryLessonDetByLessonId?lessonId="+$("#lessonId").val(),
                type:"GET",
                success:function (res) {
                    var data=res.data;
                    $("#payType").find("option[value='"+data.payType+"']").attr("selected",true);
                    $("#stock").val(data.stock);
                    $("#lessonName").val(data.lessonName);
                    $("#lessonDate").val(data.lessonDate);
                    $("#classSize").val(data.classSize);
                    $("#address").val(data.address);
                    $("#price").val(data.price);
                    $("#groupPrice").val(data.groupPrice);
                    $("#startDate").val(data.startDate);
                    $("#endDate").val(data.endDate);
                    $("#photo").val(data.photo);
                    $("#videoUrl").val(data.videoUrl);
                    $("#teacherId").val(data.teacherId);
                    var memberList=new Array();
                    memberList.push(data.teacherId);
                    sessionStorage.setItem("memberList",JSON.stringify(memberList));
                    $("#teacherName").val(data.trueName);
                    var nameList=new Array();
                    nameList.push(data.trueName);
                    sessionStorage.setItem("nameList",JSON.stringify(nameList));
                    data.hot =="1" ? $("input[type='radio'][name='hot']").eq(0).attr("checked",true) : $("input[type='radio'][name='hot']").eq(1).attr("checked",true);
                    $("#categoryId").find("option[value='"+data.categoryId+"']").attr("selected",true);
                    data.state =="1" ? $("input[type='radio'][name='state']").eq(0).attr("checked",true) : $("input[type='radio'][name='state']").eq(1).attr("checked",true);

                    //给富文本编辑器赋值
                    if(data.mdesc !="" && data.mdesc != null ){
                        tinyMCE.activeEditor.setContent(data.mdesc);
                    }
                    // $(".tinymce").attr("value",data.mdesc);
                    var temp = [];
                    //循环读取图片
                    if (data.lessonAttList != null && data.lessonAttList != "undefined") {
                        $.each(data.lessonAttList, function (i, obj) {
                            temp.push(obj.attachmentUrl);
                        });
                        //初始化图片展示
                        $("#case").attr("data-value", temp);
                    }
                    $("#case").upload(
                        function(_this,data){
                            layer.msg("图片链接："+data,{time: 5000},function(){});
                        }
                    );
                }
            })
        }
    },
};


$(document).ready(function(){
    sessionStorage.removeItem("memberList");
    sessionStorage.removeItem("nameList");
    var data=eval('(' + $(sessionStorage)[0].user +')');
    role=data.roleId;
    if("show" == queryType || "update" == queryType){
        $("#ObjId").val(lessonId);
        $("#lessonId").val(lessonId);
        gocode='/lesson/updateLesson';
    }
      var payHtml='';
      switch (lessonType) {
          case "lesson":
              type='1';
              $("#upClassSize").text("班级人数");
              $("#upLessonDate").text("课程期数");
              $("#profile_tab_9_type").addClass("icon-list-lesson");
              addLesson.queryCatAll("lesson");

              if("show" == queryType || "update" == queryType){
                  // addLesson.updateInit();
                  $("#topUpImgs").show();
                  $("#topPhoto").show();//课程图片
              }else {
                  $("#case").upload(
                      function(_this,data){
                          layer.msg("图片链接："+data,{time: 5000},function(){});
                      }
                  );
                  //图片上传
                  $("#topUpImgs").hide();
                  $("#topPhoto").hide();//课程图片
              }
              if(role == "1" || role =="2"){
                 $("#topHot").show();
              }else {
                  $("#topHot").hide();
              }
              // $("#topVideo").hide();//视频地址
              payHtml +='<option value="2">现金</option><option value="3">课时</option>';
              addLesson.addLessonInit();
              addLesson.scheduleInit();
              break;
          case "voide":
              type='2';
              $("#upLessonDate").text("章节节数");
              $("#profile_tab_9_type").addClass("icon-list-chapter");
              addLesson.queryCatAll("lessonVid");
              $("#topUpImgs").show();
              if("show" == queryType || "update" == queryType){
                  // addLesson.updateInit();
                  $("#topUpImgs").show();
                  $("#topPhoto").show();//课程图片
              }else {
                  $("#case").upload(
                      function(_this,data){
                          layer.msg("图片链接："+data,{time: 5000},function(){});
                      }
                  );
                  //图片上传
                  $("#topUpImgs").hide();
                  $("#topPhoto").hide();//课程图片
              }
              $("#topClassSize").hide();//班级人数
              $("#topStock").hide();//库存
              $("#topAddress").hide();//上课地点
              // $("#topPhoto").hide();//课程图片
              $("#topStart").hide();
              $("#topEnd").hide();
              $("#topIsGrounding").hide();
              payHtml +='<option value="2">现金</option><option value="3">课时</option>';
              addLesson.addLessonInit();
              addLesson.scheduleInit();
              break;
          case "meal":
              type='3';
              $("#myTabs_9").hide();
              $("#profile_9").hide();
              // $("#topPayType").hide();//支付方式
              $("#topHot").hide();//分类
              $("#topCate").hide();//分类
              $("#topTeacher").hide();//任课老师
              // $("#upLessonDate").text("可购课时数");
              $("#topLessonDate").hide();//期数
              $("#upClassSize").text("可购课时数");
              // $("#topClassSize").hide();//班级人数
              // $("#topStock").text();
              $("#topStock").hide();//库存
              $("#topAddress").hide();//上课地点
              $("#topPhoto").hide();//课程图片
              $("#topVideo").hide();//视频地址
              $("#topUpImgs").hide();
              $("#topIsGrounding").hide();
              payHtml +='<option value="0">单价</option><option value="1">套餐</option>';
              addLesson.addLessonInit();
              addLesson.scheduleInit();
              break;
      }

    $("#payType").html(payHtml);
});